package com.huitone.smspfm.core.filter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

import com.huitone.smspfm.logger.ExtLogger;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import com.bin.common.utils.StringUtils;
import com.huitone.smspfm.core.config.AppStaticConfigs;
import com.huitone.smspfm.core.constant.DealResult;
import com.huitone.smspfm.model.SmsEntityForMt;

/**   
* @Title BlackListFilterTask.java 
* @Package com.huitone.smspfm.core.task 
* @Description TODO(用一句话描述该文件做什么) 
* @author ybliang   
* @date 2017年6月17日 下午4:33:44 
* @version V1.0   
*/
public class BlackListFilterTask extends Thread {
	
	private ExtLogger logger = ExtLogger.create(BlackListFilterTask.class);
	
	private String moduleName = "黑名单用户过滤模块";
	
	//private byte[] moduleNameB = AppStaticConfigs.stringRedisSerializer.serialize(moduleName); 
	
	private List<SmsEntityForMt> entities = null;
	
	private CyclicBarrier barrier = null;
	
	public BlackListFilterTask(List<SmsEntityForMt> entities, CyclicBarrier barrier) {
		this.entities = entities;
		this.barrier = barrier;
	}

	@Override
	public void run() {
		
		if (entities == null) return;
		
		long start = System.currentTimeMillis();
		
		List<String> list = new ArrayList<>();
		
		int size = entities.size();
		for (int i = 0 ; i < size ; i ++) {
			
			StringBuffer buffer = new StringBuffer();
			
			SmsEntityForMt smsEntity = entities.get(i);
			
			String srvNode = StringUtils.toString(smsEntity.getSrvNode());
			String serviceCode = StringUtils.toString(smsEntity.getServiceCode());
			String userNumber = StringUtils.toString(smsEntity.getPhoneNumber());
			
			buffer.append(srvNode);
			buffer.append(":");
			buffer.append(serviceCode);
			buffer.append(":");
			buffer.append(userNumber);
			
			list.add(buffer.toString());
		}
		
		List<Long> indexes = AppStaticConfigs.scriptOpts2
				.getListLong(new DefaultRedisScript<>(AppStaticConfigs.luaBlackChecker, List.class),
						Collections.singletonList(AppStaticConfigs.configBlackListZSet), list.toArray());
		
		for (int i = 0 ; i < entities.size() ; i ++) {
			
			SmsEntityForMt entity = entities.get(i);
			
			if (indexes.get(i) == 1) {
				
				entity.setDealResultCodeMap(moduleName, DealResult.RESULT_4);
				entity.setInterceptedCode(DealResult.RESULT_4);
				entity.setInterceptedDesc(DealResult.RESULT_4_DESC);
				entity.setIntercepted(true);
				
				logger.debug("[序列号:用户号码][" + entity.getSerialno() + ":" + entity.getPhoneNumber() + "]被黑名单用户过滤器捕获,处理流程结束。");
				
			} else {
				
				entity.setDealResultCodeMap(moduleName, DealResult.RESULT0);
			}
		}
		
		long end = System.currentTimeMillis();
		
		logger.debug("黑名单用户过滤:" + (end - start) + "毫秒");
		
		try {
			barrier.await();
		} catch (InterruptedException | BrokenBarrierException e) {
			e.printStackTrace();
		}
	}

}
